// step 3 - http://en.wikipedia.org/wiki/Bzip2#Compression_stack

#include <iostream>
#include <fstream>
using namespace std;

#include "MTF.h"

bool equals(unsigned int bytes, const unsigned char *buf1, const unsigned char *buf2);

int main()
{
	const int BUFLEN = 1024;	// 1kiB
	unsigned char buffer[BUFLEN];
	ifstream fin("txt.bwt", ios_base::in | ios_base::binary);
	if(!fin.is_open()) { cerr << "error" << endl; return 0; }
	ofstream fout("txt.mtf", ios_base::out | ios_base::binary);
	if(!fout.is_open()) { cerr << "error" << endl; return 0; }
	// MTF encoding
	//  - example: "swm siisss" -->  C=(3,4,4,3,3,4,0,1,0,0)/alphabet=( ,i,m,s,w)
	unsigned char encoded[BUFLEN];
	unsigned char decoded[BUFLEN];
	streamsize read;
	while(1)
	{
		// encode 1 block
		fin.read((char *)buffer, BUFLEN);
		if((read = fin.gcount()) > 0)
		{
			MTF::Encode(buffer, read, encoded);
			fout.write((char *)encoded, read);
			MTF::Decode(encoded, read, decoded);
			if(equals(read, buffer, decoded))
				cout << "Ok" << endl;
			else
				cout << "Err" << endl;
		}
		if(fin.eof()) break;
	}
	//
	fout.close();
	fin.close();
	return 0;
}

bool equals(unsigned int bytes, const unsigned char *buf1, const unsigned char *buf2)
{
	for(unsigned int i = 0; i < bytes; i++)
		if(buf1[i] != buf2[i])
			return false;
	return true;
}